package com.example.utils;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

/*
 * @className: TransactionUtils
 * @author: chentao
 * @date: 2025/3/27 下午12:30
 * @Version: 1.0
 * @description:
 */
public class TransactionUtils {

    /***
     * 打开一个事务管理
     * @return
     */
    public static TransactionStatus begin() {
        DataSourceTransactionManager dataSourceTransactionManager = (DataSourceTransactionManager) SpringBeanUtils.getBean(DataSourceTransactionManager.class);
        return dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
    }

    /***
     * 提交事务
     * @param status
     */
    public static void commit(TransactionStatus status) {
        DataSourceTransactionManager dataSourceTransactionManager = (DataSourceTransactionManager) SpringBeanUtils.getBean(DataSourceTransactionManager.class);
        dataSourceTransactionManager.commit(status);
    }

    /***
     * 回滚事务
     * @param status
     */
    public static void rollback(TransactionStatus status) {
        DataSourceTransactionManager dataSourceTransactionManager = (DataSourceTransactionManager) SpringBeanUtils.getBean(DataSourceTransactionManager.class);
        dataSourceTransactionManager.rollback(status);
    }
}
